package com.couldsail.takeaway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.couldsail.takeaway.mapper.ProductSpecOptionsMapper;
import com.couldsail.takeaway.mapper.ProductSpecsMapper;
import com.couldsail.takeaway.mapper.ProductsMapper;
import com.couldsail.takeaway.pojo.dto.ProductSpecOptionsDTO;
import com.couldsail.takeaway.pojo.dto.ProductSpecsDTO;
import com.couldsail.takeaway.pojo.dto.ProductsDTO;
import com.couldsail.takeaway.pojo.entity.ProductSpecOptions;
import com.couldsail.takeaway.pojo.entity.ProductSpecs;
import com.couldsail.takeaway.pojo.entity.Products;
import com.couldsail.takeaway.service.ProductsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products> implements ProductsService {
    private final ProductsMapper productsMapper;
    private final ProductSpecsMapper productSpecsMapper;
    private final ProductSpecOptionsMapper productSpecOptionsMapper;
    /**
     * 依据分类id查询商品列表
     * @param categoryId
     * @return List<ProductsDTO>
     */
    @Override
    public List<ProductsDTO> getProducts(String categoryId) {
        // Step 1: 查询 Products 并排序
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId)
                .orderByAsc("sort")  // 首先按 sort 升序排序
                .orderByAsc("created_at"); // 然后按 created_at 升序排序

        List<Products> products = productsMapper.selectList(queryWrapper);
        if (products.isEmpty()) {
            return Collections.emptyList(); // 如果没有产品，直接返回空列表
        }

        // Step 2: 批量查询 ProductSpecs
        Set<String> productIds = products.stream().map(Products::getId).collect(Collectors.toSet());
        List<ProductSpecs> allProductSpecs = productSpecsMapper.selectBatchIds(productIds);

        // Step 3: 批量查询 ProductSpecOptions
        Set<String> specIds = allProductSpecs.stream().map(ProductSpecs::getId).collect(Collectors.toSet());

        QueryWrapper<ProductSpecOptions> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.in("spec_id",specIds);
        // 只有当 specIds 非空时才进行查询
        List<ProductSpecOptions> allProductSpecOptions = !specIds.isEmpty()
                ? productSpecOptionsMapper.selectList(queryWrapper1)
                : Collections.emptyList();

        // Step 4: 将 ProductSpecs 按 product_id 分组
        Map<String, List<ProductSpecs>> specsByProductId = allProductSpecs.stream()
                .collect(Collectors.groupingBy(ProductSpecs::getProductId));
        // Step 5: 将 ProductSpecOptions 按 spec_id 分组
        Map<String, List<ProductSpecOptions>> optionsBySpecId = allProductSpecOptions.stream()
                .collect(Collectors.groupingBy(ProductSpecOptions::getSpecId));
        // Step 6: 构建 DTO 并填充数据
        List<ProductsDTO> productsList = products.stream()
                .map(product -> {
                    ProductsDTO dto = new ProductsDTO();
                    BeanUtils.copyProperties(product, dto);

                    // 获取并设置 Specs
                    List<ProductSpecs> specs = specsByProductId.getOrDefault(product.getId(), Collections.emptyList());
                    List<ProductSpecsDTO> specsDTOs = specs.stream()
                            .map(ps -> {
                                ProductSpecsDTO specDto = new ProductSpecsDTO();
                                BeanUtils.copyProperties(ps, specDto);

                                // 获取并设置 Options
                                List<ProductSpecOptions> options = optionsBySpecId.getOrDefault(ps.getId(), Collections.emptyList());

                                List<ProductSpecOptionsDTO> optionsDTOs = options.stream()
                                        .map(pso -> {
                                            ProductSpecOptionsDTO optionDto = new ProductSpecOptionsDTO();
                                            BeanUtils.copyProperties(pso, optionDto);
                                            optionDto.setIsSelected(pso.getIsSelected() == 0);
                                            return optionDto;
                                        })
                                        .toList();

                                specDto.setOptions(optionsDTOs);
                                return specDto;
                            })
                            .toList();

                    dto.setSpecs(specsDTOs);
                    return dto;
                })
                .toList();

        return productsList;
    }

    /**
     * 依据商品id查询商品
     * @param id
     * @return Products
     */
    @Override
    public Products getProductId(String id) {
        return productsMapper.selectById(id);
    }
    /**
     * qi
     * @param id
     * @return Products
     */
}
